<?php

namespace addons\booking\library\order;

use addons\booking\model\UserCoupon;
use addons\booking\model\Coupon;
use addons\booking\model\Cart;
use think\Db;
use addons\booking\model\Order;
use addons\booking\model\OrderGoods as OrderGoodsModel;
//商品订单整合参数
class OrderGoods implements orderInterface
{
    public function planOrder($orderInfo, $param)
    {
        $userCoupon = null;
        $user_id = $param['user_id'];
        $cart_ids = $param['cart_ids'];
        $orderItem = [];

        //暂未加商品优惠券
        //校验领取和是否可使用
         if ($param['user_coupon_id']) {
            $userCouponModel = new UserCoupon();
            $userCoupon = $userCouponModel->checkUserOrUse($param['user_coupon_id'], $user_id);
            $orderInfo['user_coupon_id'] = $param['user_coupon_id'];
        }
       
        //订单计算购物车商品
        $list = (new Cart)->with('Goods')->where('id', 'in', $cart_ids)->select();

        if(empty($list)){
            throw new \Exception("未找到商品");
        }

        $orderInfo['nums'] = 0;
        $orderInfo['status'] = 'created';

        foreach ($list as $item) {
            if (empty($item->goods)) {
                throw new \Exception("存在失效的商品");
            }
            if ($item->goods->status != 'up') {
                throw new \Exception("存在已下架的商品");
            }
            $nums = $item->nums;           
            if ($item->goods->stocks < $nums) {
                throw new \Exception("存在库存不足的商品");
            }
            $orderInfo['nums'] = bcadd($orderInfo['nums'], $nums);
            $orderInfo['amount'] = bcadd($orderInfo['amount'], bcmul($nums, $item->goods->price, 2), 2);

            //订单商品数据
            $orderItem[] = [
                'orderid' => $orderInfo['orderid'],
                'goods_id' => $item->goods_id,
                'name' => $item->goods['name'],
                'image' => $item->goods->image,
                'price' => $item->goods->price,
                'nums' => $nums,
                'amount' => bcmul($nums, $item->goods->price, 2)
            ];
        }
        $goods_ids = array_column($list,'goods_id');
        if (!empty($userCoupon)) {
            //校验优惠券
            $couponModel = new Coupon();
            $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
                ->checkCoupon()
                ->checkOpen()
                ->checkUseTime($userCoupon['createtime'])
                ->checkConditionGoods($goods_ids, $user_id);
            //计算价格
            list($new_money, $coupon_money) = $coupon->doBuy($orderInfo['amount']);
            $orderInfo['amount'] = $new_money;
            $orderInfo['coupon_amount'] = $coupon_money;
        }

        // 启动事务
        Db::startTrans();
        try {
            //主订单表
            $orderModel = new Order();
            $orderModel->save($orderInfo);
            //订单明细
            (new OrderGoodsModel)->saveAll($orderItem);
            //减库存
            foreach ($list as $res) {
                //下单减库存
                $goods = $res->goods;
                $goods->setDec('stocks', $item->nums);
                //删除购物车
                $res->delete();
            }
             //优惠券已使用
             if(!empty($userCoupon)){
                $userCoupon->save(['is_used'=>2]);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

        return [
            'id' => $orderModel->getData('id'),
            'amount' => $orderModel->getData('amount'),
            'status' => $orderInfo['status']
        ];
    }
}
